package com.atguigu.gulimall.auth.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.LoginUserConstant;
import com.atguigu.common.utils.HttpClientUtil;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.authGitee.GiteeUser;
import com.atguigu.gulimall.auth.authGitee.ProviderToken;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
@Slf4j
public class GiteeOAuth2Controller {


    @Autowired
    private MemberFeignService memberFeignService;
    @Value("${gitee.oauth2.client_id}")
    private String clientId;

    @Value("${gitee.oauth2.client_secret}")
    private String clientSecret;

    @Value("${gitee.oauth2.redirect_uri}")
    private String redirectUri;



    @GetMapping("/callback")
    public String callback(@RequestParam("code") String code,
                           @RequestParam("state") String state,
                           Model model) {
        //用户授权信息
        ProviderToken token = new ProviderToken();
        token.setClientId(clientId);
        token.setRedirectUri(redirectUri);
        token.setClientSecret(clientSecret);
        token.setCode(code);
        token.setState(state);
        //获取token和登录的用户信息
        /*String accessToken = giteeProvider.getGiteeToken(token);
        GiteeUser giteeUser = giteeProvider.getGiteeUser(accessToken);
        model.addAttribute("user", giteeUser);
        model.addAttribute("name", giteeUser.getName());
        System.out.println(giteeUser);*/
        return "login1";
    }

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code,
                        Model model, HttpSession session) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id",clientId);
        map.put("redirect_uri",redirectUri);
        map.put("client_secret",clientSecret);
        //HttpResponse response=HttpUtils.doPost("https://gitee.com", "/oauth/token", "POST", null, null, map);
        String response = HttpClientUtil.doPost("https://gitee.com/oauth/token", map);
        //if(response.getStatusLine().getStatusCode()==200){
        if(!StringUtils.isEmpty(response)){
            //String json = EntityUtils.toString(response.getEntity());
            GiteeUser giteeUser = JSON.parseObject(response, GiteeUser.class);
            //为当前用户自动注册账号,判断是否是第一次登录,是第一次就注册
            R oauth2Login = memberFeignService.oauth2Login(giteeUser);
            if (oauth2Login.getCode()==0){
                //登录成功
                MemberRespVo data = oauth2Login.getData("GiteeUser", new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功：用户：{}", data.toString());

                session.setAttribute(LoginUserConstant.USER_LOGIN, data);
                return "redirect:http://daogumall.com";
            }else {
                return "redirect:http://auth.daogumall.com/login.html";
            }
        }else {
            return "redirect:http://auth.daogumall.com/login.html";
        }

    }
}
